package logic

import (
	"context"
	"errors"
	"fmt"
	"order/model"
	"order/utils"
	"time"

	"order/internal/svc"
	"order/order"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderCreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderCreateLogic {
	return &OrderCreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderCreateLogic) OrderCreate(in *order.OrderCreateRequest) (*order.OrderCreateResponse, error) {
	tx := model.Db
	orderInfo := model.Order{
		OrderNum: fmt.Sprintf("wsyx%d-%d", time.Now().Unix(), in.UserId),
		UserId:   in.UserId,
		SumPrice: "9.9",
		Status:   1,
	}
	result := tx.Model(&model.Order{}).Create(&orderInfo)
	if result.Error != nil {
		tx.Callback()
		fmt.Println(result.Error)
		return nil, errors.New("订单创建失败")
	}

	for _, v := range in.PurchaseGoods {
		orderGoods := model.OrderGoods{
			SonOrderNum: fmt.Sprintf("wsyx%d-%d", time.Now().Unix(), orderInfo.ID),
			OrderId:     int32(orderInfo.ID),
			GoodsSkuId:  v.GoodsSkuId,
			Number:      v.Number,
			SumPrice:    "15.99", //todo 计算金额
			Status:      1,
		}
		result := tx.Model(&orderGoods).Create(&orderGoods)
		if result.Error != nil {
			tx.Callback()
			fmt.Println(result.Error)
			return nil, errors.New("订单创建失败")
		}
	}

	return &order.OrderCreateResponse{
		OrderData: utils.OrderModelToProto(orderInfo),
	}, nil

}
